package org.ztest.guava;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

// 测试Guava EventBus
public class TestEventBus
{
    private static final Logger LOG = LoggerFactory.getLogger(TestEventBus.class);
    
    // 事件对象(自定义)
    static class TestEventObject
    {
        private String name;

        public TestEventObject(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return "TestEventObject[name=" + name + "]";
        }
    }

    // 标注订阅方法，该方法必须有且只有一个参数
    // 当对应类型的事件被触发时，该方法将被执行
    @Subscribe
    public void onSubscribe(TestEventObject event) {
        LOG.debug("Receive event: {}, Thread:", Thread.currentThread());
    }

//    // 当有不止一个方法订阅同一个事件类型时，这些订阅方法均将会触发
//    @Subscribe
//    public void onSubscribe2(TestEventObject event) {
//        System.out.println("Receive event2:" + event + ", Thread:" + Thread.currentThread());
//    }

//    // 订阅类型为Object的方法将接收任意类型的事件
//    @Subscribe
//    public void onSubscribe3(Object event) {
//        System.out.println("Receive event3:" + event + ", Thread:" + Thread.currentThread());
//    }

    // 测试普通功能
    public void test1() {
        System.out.println("Current thread:" + Thread.currentThread());
        // EventBus所有事件均在post线程中执行
        EventBus bus = new EventBus("TEST_EVENT_BUS");
        bus.register(new TestEventBus());
        bus.post(new TestEventObject("TestEventObject"));
        bus.post(new String("STRING POST"));
        bus.post(1);
    }

    // 测试性能
    public void test2() {
        EventBus bus = new EventBus("TEST_EVENT_BUS2");
        bus.register(new TestEventBus());
        long start = System.currentTimeMillis();
        final int eventCount = 10000;
        for (int i = 0; i < eventCount; i++) {
            bus.post(new TestEventObject("TestEventObject"));
        }
        System.out.println("Process " + eventCount + " events in " + (System.currentTimeMillis() - start) + "ms");
    }
}
